package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.TravelComment;
import cn.wolfcode.trip.base.domain.TravelCommentRe;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.ITravelCommentReService;
import cn.wolfcode.trip.base.service.ITravelCommentService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("travelCommentRes")
public class TravelCommentReController {

    @Autowired
    private ITravelCommentReService travelCommentReService;

    @Autowired
    private ITravelCommentService travelCommentService;

    /**
     * 通过当前评论的id获取其下面的所有二级评论
     * @param travelCommentId
     * @return
     */
    @GetMapping("/{travelCommentId}")
    public JsonResult getCommentRe(@PathVariable("travelCommentId") Long travelCommentId){
        JsonResult jsonResult = new JsonResult();
        List<TravelCommentRe> list = travelCommentReService.queryBytravelCommentId(travelCommentId);
        return jsonResult.setResult(list);
    }

    /**
     * 保存新的叠加评论
     * @param travelCommentId
     * @param commentContent
     * @return
     */
    @PostMapping
    public JsonResult saveCommentRe(@RequestParam Long travelCommentId, @RequestParam String commentContent){
        JsonResult jsonResult = new JsonResult();
        try {
            TravelCommentRe travelCommentRe = new TravelCommentRe();
            //设置评论用户
            User currentUser = UserContext.getCurrentUser();
            travelCommentRe.setUser(currentUser);
            //设置评论时间
            travelCommentRe.setCreateTime(new Date());
            //设置评论内容
            travelCommentRe.setContent(commentContent);
            //设置该评论的上级评论的id
            TravelComment travelComment = travelCommentService.getByTravelCommentId(travelCommentId);
            travelCommentRe.setTravelComment(travelComment);
            //设置状态(未读)
            travelCommentRe.setStatus(TravelCommentRe.UNREAD);
            travelCommentReService.saveCommentRe(travelCommentRe);
            Integer replyCount = travelCommentService.getReplyCount(travelCommentId);
            if (replyCount==null){
                replyCount=0;
            }
            travelCommentService.updateReplyCount(replyCount+1,travelCommentId);
            return jsonResult;
        }catch (Exception e){
            e.printStackTrace();
            return jsonResult.mark("未知错误");
        }

    }



}
